import React, { useState, useEffect } from 'react';
import { memberAPI, userAPI } from '../services/api';

function MemberManagement() {
  const [memberApplications, setMemberApplications] = useState([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const pageSize = 10;

  useEffect(() => {
    fetchMemberApplications();
  }, [currentPage]);

  const fetchMemberApplications = async () => {
    try {
      setLoading(true);
      const response = await memberAPI.getMemberApplications(currentPage, pageSize);
      
      if (response && response.result) {
        setMemberApplications(response.result.records || []);
        setTotalPages(Math.ceil((response.result.total || 0) / pageSize));
      }
    } catch (error) {
      console.error('获取会员申请列表失败:', error);
      alert('获取会员申请列表失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const handleApproveApplication = async (applicationId, userId) => {
    if (!alert('确定要批准这个会员申请吗？')) {
      return;
    }

    try {
      // 批准申请
      const response = await memberAPI.approveApplication(applicationId);
      
      if (response && (response.code === 200 || response.success)) {
        alert('会员申请已批准');
        fetchMemberApplications(); // 刷新列表
      } else {
        alert(response?.message || '批准失败，请稍后重试');
      }
    } catch (error) {
      console.error('批准申请失败:', error);
      alert('批准失败，请稍后重试');
    }
  };

  const handleRejectApplication = async (applicationId) => {
    if (!alert('确定要拒绝这个会员申请吗？')) {
      return;
    }

    try {
      const response = await memberAPI.rejectApplication(applicationId);
      
      if (response && (response.code === 200 || response.success)) {
        alert('会员申请已拒绝');
        fetchMemberApplications(); // 刷新列表
      } else {
        alert(response?.message || '拒绝失败，请稍后重试');
      }
    } catch (error) {
      console.error('拒绝申请失败:', error);
      alert('拒绝失败，请稍后重试');
    }
  };

  const handlePageChange = (newPage) => {
    if (newPage >= 1 && newPage <= totalPages) {
      setCurrentPage(newPage);
    }
  };

  const getStatusText = (memberFlag) => {
    switch (memberFlag) {
      case 0:
        return { text: '待审核', className: 'pending' };
      case 1:
        return { text: '已批准', className: 'approved' };
      case 2:
        return { text: '已拒绝', className: 'rejected' };
      default:
        return { text: '未知', className: 'unknown' };
    }
  };

  return (
    <div className="member-management">
      <div className="management-header">
        <h3>会员管理</h3>
        <button className="refresh-btn" onClick={fetchMemberApplications}>
          刷新列表
        </button>
      </div>

      {loading ? (
        <div className="loading">加载中...</div>
      ) : (
        <>
          <div className="applications-list">
            {memberApplications.length === 0 ? (
              <div className="no-applications">暂无会员申请</div>
            ) : (
              <div className="applications-table">
                <div className="table-header">
                  <span className="col-user">用户ID</span>
                  <span className="col-email">邮箱</span>
                  <span className="col-apply-date">申请时间</span>
                  <span className="col-status">状态</span>
                  <span className="col-actions">操作</span>
                </div>
                
                {memberApplications.map((application) => {
                  const status = getStatusText(application.memberFlag);
                  return (
                    <div key={application.id} className="table-row">
                      <span className="col-user">{application.userId}</span>
                      <span className="col-email">{application.userEmail || '未知'}</span>
                      <span className="col-apply-date">
                        {new Date(application.applyAt).toLocaleDateString()}
                      </span>
                      <span className="col-status">
                        <span className={`status-badge ${status.className}`}>
                          {status.text}
                        </span>
                      </span>
                      <span className="col-actions">
                        {application.memberFlag === 0 && (
                          <>
                            <button 
                              className="action-btn approve-btn"
                              onClick={() => handleApproveApplication(application.id, application.userId)}
                            >
                              批准
                            </button>
                            <button 
                              className="action-btn reject-btn"
                              onClick={() => handleRejectApplication(application.id)}
                            >
                              拒绝
                            </button>
                          </>
                        )}
                        {application.memberFlag !== 0 && (
                          <span className="action-disabled">已处理</span>
                        )}
                      </span>
                    </div>
                  );
                })}
              </div>
            )}
          </div>

          {/* 分页 */}
          {totalPages > 1 && (
            <div className="pagination">
              <button 
                className="page-btn"
                onClick={() => handlePageChange(currentPage - 1)}
                disabled={currentPage === 1}
              >
                上一页
              </button>
              
              <span className="page-info">
                第 {currentPage} 页，共 {totalPages} 页
              </span>
              
              <button 
                className="page-btn"
                onClick={() => handlePageChange(currentPage + 1)}
                disabled={currentPage === totalPages}
              >
                下一页
              </button>
            </div>
          )}
        </>
      )}
    </div>
  );
}

export default MemberManagement;
